package cn.kgc.springbootdemo.config.dingding;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.kgc.springbootdemo.util.RequestIpUtils;
import cn.kgc.springbootdemo.util.StringToListUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <h3>springbootdemo</h3>
 * <p>钉钉异步推送消息类</p>
 *
 * @author : DongZeJian
 * @date : 2021-01-29 23:45
 **/
@Component
@Slf4j
public class SysncTaskManage {

    @Autowired
    private DingDingProperties dingDingProperties;

    @Async
    public void sendExamExceptionNotice(String url, String level, String errMsg) {
        if (StrUtil.isEmpty(errMsg)) {
            return;
        }
        //如果开启钉钉通知发送钉钉
        if (dingDingProperties.getEnable()) {
            //钉钉通知
            DingDingNoticeTextEntity dingDingNoticeTextEntity = new DingDingNoticeTextEntity();

            //钉钉警告消息实体
            DingDingMessageEntity dingDingMessageEntity = new DingDingMessageEntity();
            dingDingMessageEntity.setEnvironment(dingDingProperties.getEnvironment());
            dingDingMessageEntity.setHost(RequestIpUtils.getIpAddr());
            dingDingMessageEntity.setUrl(url);
            dingDingMessageEntity.setProject(dingDingProperties.getCustomer());
            dingDingMessageEntity.setErrMsg(errMsg);
            dingDingMessageEntity.setLevel(level);
            dingDingMessageEntity.setWarnInfo(dingDingProperties.getInfo()+"-告警");
            dingDingMessageEntity.setLocalDateTime(DateUtil.date());
            dingDingNoticeTextEntity.setDingDingMessageEntity(dingDingMessageEntity);

            dingDingNoticeTextEntity.setIsAtAll(dingDingProperties.getIsAtAll());
            List<String> mobileList = StringToListUtils.stringToList(dingDingProperties.getAtMobiles(), StrUtil.COMMA);
            dingDingNoticeTextEntity.setAtMobiles(mobileList);
            DingdingUtils.sendToDingding(dingDingNoticeTextEntity.getJSONObjectString(), dingDingProperties.getNotice());
        }
    }
}
